package controllers

import (
	"myapp/config"
	"myapp/dal/model"
	"myapp/dal/query"
	"myapp/pkg"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"gorm.io/gorm"
)

func getRoomId(obj_user_id1, user_id1 int32) *model.ChatRoom {
	ru1 := query.ChatRoomUser.As("ru1")
	ru2 := query.ChatRoomUser.As("ru2")
	rm := query.ChatRoom.As("rm")
	room, _ := rm.Join(ru1, ru1.RoomID.EqCol(rm.ID)).Join(ru2, ru2.RoomID.EqCol(ru1.RoomID), ru2.ID.NeqCol(ru1.ID)).Select(rm.ID, rm.Name, rm.UserID, rm.UpdatedAt).Where(ru1.UserID.Eq(obj_user_id1), ru2.UserID.Eq(user_id1)).Take()
	if room == nil {
		room = &model.ChatRoom{
			Name:   cast.ToString(obj_user_id1) + "-" + cast.ToString(user_id1),
			UserID: user_id1,
		}
		query.ChatRoom.Create(room)

		ru1 := &model.ChatRoomUser{
			RoomID: room.ID,
			UserID: obj_user_id1,
		}
		query.ChatRoomUser.Create(ru1)

		ru2 := &model.ChatRoomUser{
			RoomID: room.ID,
			UserID: user_id1,
		}
		query.ChatRoomUser.Create(ru2)
	}

	return room
}

func GetRoomIdHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)
		obj_user_id, _ := c.GetQuery("obj_user_id")
		obj_user_id1 := cast.ToInt32(obj_user_id)

		userId, _ := c.Get("userID")
		user_id := 0
		if v, ok := userId.(uint); ok {
			user_id = int(v)
		}
		user_id1 := int32(user_id)

		room := getRoomId(obj_user_id1, user_id1)

		c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
			"room": room,
		}})
	}
}

func RoomListHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		pagestr, _ := c.GetQuery("page")
		page1, _ := strconv.Atoi(pagestr)
		if page1 <= 1 {
			page1 = 1
		}

		userId, _ := c.Get("userID")
		user_id := 0
		if v, ok := userId.(uint); ok {
			user_id = int(v)
		}

		querys := query.ChatRoomUser.Where(query.ChatRoomUser.UserID.Eq(int32(user_id)))

		offset := (page1 - 1) * 10
		needs, _, _ := querys.Order(query.ChatRoomUser.UpdatedAt.Desc()).FindByPage(offset, 10)

		// 将查询结果转换为自定义结构体
		var customNeeds []map[string]any
		for _, need := range needs {

			room, _ := query.ChatRoom.Where(query.ChatRoom.ID.Eq(need.RoomID)).Take()

			var musts []any
			var filters []any

			filters = append(filters, map[string]any{"term": map[string]any{
				"room_id": need.RoomID,
			}})

			filters = append(filters, map[string]any{"range": map[string]any{
				"time": map[string]any{
					"gt": need.UpdatedAt,
				},
			}})

			new := pkg.EsManager{}.Count(config.Conf.EsChatMessageIndex, musts, filters)

			up := query.UserProfile.As("up")
			cu := query.ChatRoomUser.As("cu")

			toUser, _ := up.Join(cu, cu.UserID.EqCol(up.UserID)).Select(up.ALL).Where(cu.RoomID.Eq(need.RoomID), cu.ID.Neq(need.ID)).Take()

			age := time.Now().Year() - int(toUser.Birthday)
			time, _ := pkg.FormatTime(room.UpdatedAt.Format("2006-01-02 15:04:05"), false)
			o := map[string]any{
				"nickname":    toUser.Nickname,
				"avatar":      toUser.Avatar,
				"obj_user_id": toUser.UserID,
				"city":        toUser.City,
				"age":         age,
				"newmsg":      room.Newmsg,
				"time":        time,
				"new":         new.Count,
			}

			customNeeds = append(customNeeds, o)
		}

		c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
			"needs": customNeeds,
		}})
	}
}

func CallHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)
		obj_user_id, _ := c.GetQuery("obj_user_id")
		obj_user_id1 := cast.ToInt32(obj_user_id)

		userId, _ := c.Get("userID")
		user_id := 0
		if v, ok := userId.(uint); ok {
			user_id = int(v)
		}
		user_id1 := int32(user_id)

		call, _ := query.Call.Where(query.Call.ObjUserID.Eq(obj_user_id1), query.Call.UserID.Eq(user_id1)).Take()
		if call != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 1,
				"msg":  "已经向TA打过招呼了",
			})
			return
		}

		user, _ := query.UserProfile.Where(query.UserProfile.UserID.Eq(user_id1)).Take()

		call = &model.Call{
			ObjUserID: obj_user_id1,
			UserID:    user_id1,
		}
		query.Call.Create(call)

		room := getRoomId(obj_user_id1, user_id1)
		cont := pkg.Content{
			Type:    "call",
			Content: user.Nickname + " 向你打招呼了",
			UserId:  cast.ToString(user_id1),
			Name:    user.Nickname,
			Avatar:  user.Avatar,
			Time:    time.Now(),
			RoomId:  cast.ToString(room.ID),
		}
		pkg.EsManager{}.Add(config.Conf.EsChatMessageIndex, time.Now().GoString(), cont)

		c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
			"room": call,
		}})
		return
	}
}
